package com.shop.cereshop.app.tencent.im.delay.handler;

import com.shop.cereshop.app.dao.tim.transfer.TransferOrderMapper;
import com.shop.cereshop.app.tencent.im.model.transfer.TransferOrder;
import com.shop.cereshop.app.tencent.im.delay.constant.TaskType;
import com.shop.cereshop.app.tencent.im.delay.model.DelayedTask;
import com.shop.cereshop.app.tencent.im.service.TransferOrderService;
import com.shop.cereshop.commons.enums.RefundTypeEnum;
import com.shop.cereshop.commons.tencent.im.enums.transfer.TransferOrderStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @description:  转账过期自动取消任务处理器
 * @author zdd
 * @date 2025/9/24 10:53
 * @version 1.0
 */
@Component
@Slf4j
public class TransferOrderTaskHandler implements DelayedTaskHandler {

    @Resource
    private TransferOrderMapper transferOrderMapper;
    @Resource
    private TransferOrderService transferOrderService;


    @Override
    public String getTaskType() {
        return TaskType.TRANSFER_ORDER;
    }

    @Override
    public boolean handle(DelayedTask task) {
        String transferId = task.getTaskId();
        log.info("开始执行过期未领取的转账退款: {}", transferId);

        // 幂等 + 状态检查，因为用户可能在“到期前1秒领取”，而消息已到期进入队列。消费时必须二次校验状态，避免误取消。
        if (isNoActionNeeded(transferId)) {
            log.info("转账订单 [{}] 已处理或不存在，跳过退款", transferId);
            return true;
        }

        // 执行过期未领取的转账退款
        boolean success = transferOrderService.refund(transferId, RefundTypeEnum.EXPIRED.getCode());
        if (success) {
            log.info("过期未领取的转账退款成功: {}", transferId);
            transferOrderService.modifyTimMsg(transferId);
        } else {
            log.error("过期未领取的转账退款失败: {}", transferId);
        }
        return success;
    }

    /**
     * 判断转账订单是否不用处理退款
     *
     * @param transferId 转账订单ID
     * @return true: 不用处理，false: 需要处理
     */
    public boolean isNoActionNeeded(String transferId) {
        TransferOrder transferOrder = transferOrderMapper.selectById(transferId);
        if (transferOrder == null) {
            return true;
        }
        // 空值检查
        if (transferOrder.getExpireTime() == null || transferOrder.getStatus() == null) {
            return true;
        }
        // 判断是否已过期且待领取状态（过期时间 < 当前时间，且状态已经是待领取）
        boolean isExpiredAndNotReceived = transferOrder.getExpireTime().isBefore(LocalDateTime.now())
                && TransferOrderStatusEnum.PENDING_RECEIVED.getCode().equals(transferOrder.getStatus());
        if (isExpiredAndNotReceived) {
            return false;
        }
        return true;
    }

}
